class ProjectsController < ApplicationController
  before_filter :find_project,  :except => [:index, :new, :create]  
  before_filter :find_customer_user,  :only => [:show, :new, :edit,:create,:update]  
  layout "gestion"

  access_control do
    allow :team_leader
    allow :chief_of_staff
  end

  # GET /projects
  def index
    @projects = Project.all
  end

  # GET /projects/1
  def show
  	@customer = Customer.find(@project.client_id)
  	@customer_final = Customer.find(@project.final_client_id)
  	@responsible = User.find(@project.responsible_id)
  end

  # GET /projects/new
  def new
    @project = Project.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  def create
    @project = Project.new(params[:project])
    @tasksGlobal = Task.find(:all, :conditions => { :is_global => true })
    
    if @project.save
      	redirect_to(@project)
   		@tasksGlobal.each() do |task|
			@task = ProjectTask.new( :project_id => @project.id, :task_id => task.id ) 
			@task.save   	
		end
	else
      	render :action => "new"
     end
  end

  # PUT /projects/1
  def update
      if @project.update_attributes(params[:project])
        redirect_to(@project)
      else
      	render :action => "edit"
      end
  
  end

  # DELETE /projects/1
  def destroy
    @taskProject = ProjectTask.find(:all, :conditions => { :project_id => params[:id] }) 
    @project.destroy
   
   	@taskProject.each() do |task|
		task.destroy    	
    end
    redirect_to(projects_url)
  end
  
  # Ajout de tache au projet
  def add_tasks
    @project_task = ProjectTask.new
    @tasks = Task.all
  end
  
  def add
    @project_task = ProjectTask.new( :project_id => params[:project], :task_id => params[:task] )
    
      if @project_task.save
        redirect_to(show_tasks_project_path(params[:project]))
      else
      	render :action => "add"
     end
    end
    
   def show_tasks
    @taskProject = ProjectTask.find(:all, :conditions => { :project_id => params[:id] }) 
   end
   
   def destroy_tasks
    @project_task = ProjectTask.find(params[:task])
    @project_task.destroy
    redirect_to(show_tasks_project_path(@project))
    end

private 

	def find_project 
		@project = Project.find(params[:id])  
	end 
	
	def find_customer_user 
		 @customers = Customer.all
    	 @employees = User.all
	end 


end
